import request from '@/util/request'
import axios from 'axios'

export const generatorAdd = (data: any) => {
  return request({
    url: '/generator',
    method: 'POST',
    data: data
  })
}
export const generatorRemove = (id: number) => {
  return request({
    url: '/generator',
    method: 'DELETE',
    params: {
      id: id
    }
  })
}
export const generatorModify = (data: any) => {
  return request({
    url: '/generator',
    method: 'PUT',
    data: data
  })
}
export const generatorColumnsModify = (id: number, data: any) => {
  return request({
    url: '/generator/columns',
    method: 'PUT',
    data: data,
    params: {
      id: id
    }
  })
}
export const generatorFind = (data: any, pageInfo: any) => {
  return request({
    url: '/generator/list',
    method: 'GET',
    params: {
      ...data, ...pageInfo
    }
  })
}
export const generatorFindById = (id: number) => {
  return request({
    url: '/generator',
    method: 'GET',
    params: {
      id: id
    }
  })
}
export const generatorPreview = (id: number) => {
  return request({
    url: '/generator/preview',
    method: 'GET',
    params: {
      id: id
    }
  })
}

export const generatorDownload = (id: number, model: string | null, subTableId: string | null, associationKey: string | null) => {
  const data = axios.get('/api/generator/download', {
    headers: {
      token: localStorage.getItem('token')
    },
    params: {
      id: id,
      model: model,
      subTableId: subTableId,
      associationKey: associationKey
    },
    responseType: 'blob'
  })
  data.then((result) => {
    const data = result.data as Blob
    //@ts-ignore
    const disposition = result.headers.get('content-disposition') as string
    const index = disposition.indexOf('=')
    const filename = disposition.substring(index + 1)

    const src = window.URL.createObjectURL(data)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.setAttribute('download', filename)
    link.href = src
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(src)
  })
}
